package com.tone.ji_volunteer.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.tone.ji_volunteer.pojo.Result;
import com.tone.ji_volunteer.util.JWT;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author tone(ang)
 * version 1.0
 */
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //获取url

        //判断是否为登录请求
        if(request.getRequestURL().toString().contains("/login")){
            System.out.println("正在登录。。。");
            return true;
        }
        //获取请求头token
        String token = request.getHeader("Authorization");
        System.out.println("token: " + token);

        if(!StringUtils.hasLength(token)){
            //不存在token
            System.out.println("不存在token");
            Result result = Result.error("NOT_LOGIN");
            //将result 转为json格式相应
            String res = JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(res);
            return false;
        }
        //token存在的情况下需要解析token
        try{
            Claims claims = JWT.parseJwt(token);
            System.out.println("claims :" + claims);
        }catch (Exception e){
            System.out.println("token 错误");
            Result result = Result.error("NOT_LOGIN");
            //将result 转为json格式相应
            String res = JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(res);
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("post...");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("after...");
    }
}
